import React, { useEffect, useState, useRef, useCallback } from 'react';
import { connect } from 'react-redux';
import { View, Text, Image, ScrollView, Button } from '@tarojs/components';
import Taro, { getCurrentInstance, useDidShow } from '@tarojs/taro';
import { debounce } from '@/utils/helper';
import utils from '@/utils/index';
import { sourceUrl } from '@/config';
import pNotice from '@/images/common/notice.png';
import pCheaper from '@/images/taihuHomePage/cheaper.png';
import pNewShop from '@/images/taihuHomePage/newShop.png';
import pTopName from '@/images/taihuHomePage/topName.png';
import pStar from '@/images/taihuHomePage/star1.png';
import pZhekou from '@/images/common/zhekou.png';
import pTuancanbiaoqian from '@/images/common/tuancanbiaoqian.png';
import pRightGray from '@/images/common/rightGray.svg';
import Imagelocation from '@/components/Imagelocation';
import Search from '@/components/Search';
import Advert from '@/components/Advert';
import { WrapPageLoadLoading } from '@/components/PageLoadLoading';
import UnusualContain from '@/pages/mainPages/unusualContain/index';
import ProductTitle from '@/components/product/ProductTitle';
import Tabs from './tabs';
import './homePage.scss';
import MenuTabs from '../menuTabs/index';
import CartNum from '../cartNum';
import StandServiceTags from '../../../components/StandServiceTags';

let statusBarHeight = Taro.$statusBarHeight;
if (Taro.$isH5) {
  statusBarHeight = 44;
}

const categoryList = [
  { value: 0, subLabel: '潮玩享乐', label: '生活' },
  { value: 1, subLabel: '安心到家', label: '外卖' },
  { value: 2, subLabel: '天天优惠', label: '商城' },
];

const goLocalShopDetail = (shopId) => {
  let url = '/mainSubPack/shopInfo/index?orgId=' + shopId;
  Taro.navigateTo({
    url,
  });
};

const goShopDetail = (shopId, merchantId) => {
  let url =
    '/mainSubPack/takeOutShop/index' + '?' + 'orgId=' + shopId + '&merchantId=' + merchantId;
  Taro.navigateTo({
    url,
  });
};

const HomePage = ({
  dispatch,
  cheaperProductList = [],
  takeOutOrgList = [],
  shopProductList = [],
  takeOutOrgFinished = false,
  shopProductListFinished = false,
  localOrgList = [],
  localOrgFinished = false,
  navList = [],
  newShopOrgList = [],
}) => {
  const [currentTab, setCurrentTab] = useState(0);
  const [shouldShow, setShouldShow] = useState(false);
  const [curLocation, setCurLocation] = useState(null);
  const urlParms = useRef({ display: false });

  const pageNavigateTo = (menuItem) => {
    let { name, firstIndustryId } = menuItem;
    let url = menuItem.url || '';
    let pageIdx = url.indexOf('shopList');
    if (pageIdx != -1) {
      dispatch({
        type: 'takeOut/setTakeOutItemList',
        payload: {
          takeOutItemOrgList: [],
          takeOutItemOrgPagination: {},
          takeOutItemOrgParams: {},
          takeOutItemOrgFinished: false,
        },
      });
      dispatch({
        type: 'otherApi/setShopListClassifyParams',
        payload: { firstIndustryId, pageName: 'shopList', text: name },
      });
    }

    url.length > 0 &&
      Taro.navigateTo({
        url,
      });
  };

  const showNextPageNews = debounce(() => {
    switch (currentTab) {
      case 0:
        !localOrgFinished && getLocalOrgList();
        break;
      case 1:
        !takeOutOrgFinished && getTakeOutOrgList();
        break;
      case 2:
        !shopProductListFinished && getShopProductList();
        break;
      default:
        break;
    }
  }, 1200);

  const getNavList = () => {
    dispatch({
      type: 'otherApi/getNavListModel',
      payload: {},
    });
  };

  // 前往新店日历
  const goToNewShopTimeline = useCallback(() => {
    let url = `/mainSubPack/newShopTimeline/index`;
    Taro.navigateTo({
      url,
    });
  }, []);

  const goToOtherPageByLink = useCallback((url) => {
    Taro.navigateTo({
      url,
    });
  }, []);

  useDidShow(() => {
    Taro.setTabbarIndex(0);
    let unusualInfo = utils.getLocalStorage('unusualInfo');
    if (unusualInfo !== null) {
      utils.setLocalStorage('unusualInfo', null);
    }
  });

  useEffect(() => {
    urlParms.current = getCurrentInstance().router.params || {};
    if (Taro.$isH5 && urlParms.current.from == 'wxPay') {
    } else {
      if (navList.length == 0) {
        getNavList();
      }
      if (cheaperProductList.length === 0) {
        getCheaperProductList();
      }
      let localLocation = utils.getLocalEffectLocation();
      if (localLocation) {
        const { latitude, longitude } = localLocation;
        setCurLocation({ latitude, longitude });
      } else {
        if (localOrgList.length === 0) {
          getLocalOrgList();
        }
        if (takeOutOrgList.length === 0) {
          getTakeOutOrgList();
        }
      }
      if (shopProductList.length === 0) {
        getShopProductList();
      }
    }
    setShouldShow(true);
  }, []);

  useEffect(() => {
    if (curLocation) {
      getNewShopList();
      getLocalOrgList();
      getTakeOutOrgList();
    }
  }, [curLocation]);

  useEffect(() => {
    if (!curLocation && shouldShow) {
      getLocation();
    }
  }, [shouldShow]);

  const getCheaperProductList = () => {
    dispatch({
      type: 'productList/getCheaperProductList',
      payload: { page: 1, pageSize: 4 },
    });
  };

  const getNewShopList = () => {
    const { latitude, longitude } = curLocation ?? {};
    if (!latitude) {
      return;
    }

    return dispatch({
      type: 'otherApi/fetchNewShopOrgList',
      payload: {
        pageSize: 10,
        isLocal: 1,
        lat: latitude,
        lon: longitude,
        sortType: 4,
      },
    });
  };

  const getLocalOrgList = () => {
    let params = { pageSize: 20, alias: 'localLife' };
    if (curLocation) {
      const { latitude, longitude } = curLocation;
      params = { pageSize: 20, alias: 'localLife', lat: latitude, lon: longitude };
    }
    dispatch({
      type: 'otherApi/getLocalOrgListModel',
      payload: params,
    });
  };

  const getTakeOutOrgList = () => {
    let params = { pageSize: 20, alias: 'localDelivery' };
    if (curLocation) {
      const { latitude, longitude } = curLocation;
      params = { pageSize: 20, alias: 'localDelivery', lat: latitude, lon: longitude };
    }
    dispatch({
      type: 'takeOut/getTakeOutOrgListModel',
      payload: params,
    });
  };

  const getShopProductList = () => {
    dispatch({
      type: 'productList/getShopProductList',
      payload: { pageSize: 20, alias: 'homeShoppingMall' },
    });
  };

  const getLocation = () => {
    Taro.getLocation({
      type: 'gcj02',
      isHighAccuracy: true,
      timeout: 5000,
      success: (res) => {
        const { latitude, longitude } = res;
        const timeStamp = new Date().getTime();
        setCurLocation({ latitude, longitude });
        utils.setLocalStorage('location', { latitude, longitude, timeStamp });
      },
      fail: () => {},
    }).catch(console.warn);
  };

  const handleTabChanged = (index) => {
    setCurrentTab(index);
  };

  const handleSearch = () => {
    Taro.navigateTo({ url: '/mainSubPack/searchResult/index' });
  };

  if (Taro.$isH5 && urlParms.current.from == 'wxPay') {
    return <GoOrederDetail orderId={urlParms.current.orderId} />;
  }

  let bottomHight = Taro.$bottomHight;
  if (Taro.$isH5 && window.history.length == 1 && Taro.$isIphoneX) {
    bottomHight = true;
  }

  let unusualInfo = utils.getLocalStorage('unusualInfo');

  return (
    <View className="totalPage_homePage">
      {!Taro.$isH5 && <CartNum />}

      {!Taro.$isH5 && (
        <View className="topPage stricky" style={{ paddingTop: statusBarHeight + 'px' }}>
          <Image className="topBar" src={pTopName} />
        </View>
      )}
      <View className="fontPage">
        {unusualInfo ? (
          <UnusualContain unusualInfo={unusualInfo} />
        ) : (
          <ScrollView
            className={['contentPage', bottomHight && 'high'].join(' ')}
            scrollY
            lowerThreshold={240}
            onScrollToLower={showNextPageNews}
          >
            <View className={['homePage', Taro.$isH5 && 'h5Position'].join(' ')}>
              {Taro.$isH5 && (
                <View className="topPage" style={{ paddingTop: statusBarHeight + 'px' }}>
                  <Image className="topBar" src={pTopName} />
                </View>
              )}
              <Search className="searchCnt" onlyRedirect handleSearch={handleSearch} />

              <Advert alias="_sylb" />

              <View className="swiperServices">
                <View className="serviceList">
                  {navList.length > 0 &&
                    navList.map((item, idx) => (
                      <View className="serviceArea" key={'serviceArea' + idx}>
                        <View className="service" onClick={() => pageNavigateTo(item)}>
                          <Image className="serviceIcon" src={item.imgUrl} />
                          <View className="serviceText">{item.name}</View>
                        </View>
                      </View>
                    ))}
                </View>
              </View>

              <View className="cp">
                <Image
                  className="cpIcon"
                  src="https://ht-fine-static.oss-cn-beijing.aliyuncs.com/weapp/aNeedUp/cp.jpg"
                  onClick={() => goToOtherPageByLink('/giftCardSubPack/couponCenter/index')}
                />
              </View>

              <View className="cheaperArea">
                <View
                  className="headerLine"
                  onClick={() => Taro.navigateTo({ url: '/pages/mainPages/cheaper/index' })}
                >
                  <Image className="title" src={pCheaper} />
                  <View className="more">
                    <Text className="text">更多低价限时抢购</Text>
                    <Image className="iconRight" src={pRightGray} />
                  </View>
                </View>
                <View
                  className={['productList', cheaperProductList.length < 4 && 'prolm'].join(' ')}
                >
                  {cheaperProductList.length > 0 &&
                    cheaperProductList.slice(0, 4).map((product, index) => (
                      <View
                        className={['product', cheaperProductList.length < 4 && 'prom'].join(' ')}
                        onClick={() => utils.goGoodDetail(product, dispatch)}
                        key={'cheaperProduct_' + index}
                      >
                        <View className="upImg">
                          <Imagelocation
                            className="picture"
                            src={
                              product.url?.indexOf('http') === 0
                                ? product.url
                                : sourceUrl + product.url
                            }
                          />
                          {product.activityType === 3 && (
                            <Image className="activeIcon zhekou" src={pZhekou} />
                          )}
                        </View>
                        <View className="priceLineCurrent">¥{product.price}</View>
                        <View className="priceLineOrigin">¥{product.maxPrice}</View>
                      </View>
                    ))}
                </View>
              </View>

              <View className="newShopArea">
                <View className="headerLine">
                  <Image className="title" src={pNewShop} />
                  <View className="more" onClick={goToNewShopTimeline}>
                    <Text className="text">更多新店</Text>
                    <Image className="iconRight" src={pRightGray} />
                  </View>
                </View>
                <View className="shopList">
                  {newShopOrgList.length > 0 &&
                    newShopOrgList
                      .slice(0, 4)
                      .map((shop, index) => (
                        <Imagelocation
                          className="shopImg"
                          type="shop"
                          onClick={() => goLocalShopDetail(shop.id)}
                          src={shop.logo?.indexOf('http') === 0 ? shop.logo : sourceUrl + shop.logo}
                          key={'newShop_' + index}
                        />
                      ))}
                </View>
              </View>

              <View className="classType">
                <Tabs
                  tabsList={categoryList}
                  getCurrentTab={handleTabChanged}
                  defaultTab={currentTab}
                />
              </View>

              <View className="listContent">
                {currentTab == 0 && <LocalOrg dataList={localOrgList} />}
                {currentTab == 1 && <RecTakeOutOrg dataList={takeOutOrgList} />}
                {currentTab == 2 && <RecProduct dataList={shopProductList} dispatch={dispatch} />}
              </View>

              {((currentTab == 0 && localOrgFinished && localOrgList.length > 8) ||
                (currentTab == 1 && takeOutOrgFinished && takeOutOrgList.length > 8) ||
                (currentTab == 2 && shopProductListFinished && shopProductList.length > 8)) && (
                <View className="end">- 我是有底线的 -</View>
              )}
            </View>
          </ScrollView>
        )}
        <MenuTabs tabIndex={0} />
      </View>
    </View>
  );
};

const GoOrederDetail = ({ orderId }) => {
  const orderDetailRef = useRef(null);

  const goOrderDetail = () => {
    let url = '/orderSubPack/orderDetail/index?orderId=' + orderId;
    window.location.href = url;
  };

  useEffect(() => {
    orderDetailRef && orderDetailRef.current.click();
  }, []);

  return (
    <View className="totalPage_homePage">
      <Button className="orderDetail" ref={orderDetailRef} onClick={goOrderDetail}></Button>
    </View>
  );
};

const LocalOrg = ({ dataList = [] }) => {
  return (
    <View className="storeList" key="LocalOrg">
      {dataList.length > 0 &&
        dataList.map((shop) => (
          <View
            className="shop localOrg"
            key={'localOrgShop' + shop.id + Math.random()}
            onClick={() => goLocalShopDetail(shop.id)}
          >
            {shop.activityList &&
              shop.activityList.length > 0 &&
              shop.activityList.map((activity, idx) => {
                let src = '';
                if (activity.type == 1) {
                  //团餐
                  src = pTuancanbiaoqian;
                }
                if (activity.isShow == 1) {
                  return <Image className="tcIcon" src={src} key={'localOrgActivity' + idx} />;
                } else {
                  return null;
                }
              })}
            <View className="left">
              <Imagelocation className="shopIcon" src={shop.logo} type="shop" />
            </View>
            <View className="right">
              <View className="name">{shop.name}</View>
              <View className="info">
                <View className="infoLeft">
                  <Image
                    className="starIcon"
                    src={typeof shop.grade !== 'undefined' ? pStar : ''}
                  />
                  <Text className="starNum">{shop.grade || ''}</Text>
                </View>
                <View className="infoRight">
                  <Text className="distance">
                    {typeof shop.distance !== 'undefined' ? shop.distance + 'km' : ''}
                  </Text>
                </View>
              </View>

              <StandServiceTags className="tags" serviceTags={shop.serviceTags} />

              <View className="industry">{shop.secondIndustryName || ''}</View>
              <View className="notice">
                {shop.notice && shop.notice.length > 0 && (
                  <>
                    <Text>店铺</Text>
                    <Image className="noticeIcon" src={pNotice} />
                    <Text>：{shop.notice}</Text>
                  </>
                )}
              </View>
              {shop.policy && shop.policy.length > 0 && (
                <View className="manjianLine">
                  {shop.policy.map((item, index) => (
                    <Text className="manjian" key={'localOrgManjian' + index}>
                      {item}
                    </Text>
                  ))}
                </View>
              )}
            </View>
          </View>
        ))}
    </View>
  );
};

const RecTakeOutOrg = ({ dataList = [] }) => {
  return (
    <View className="storeList" key="RecTakeOutOrg">
      {dataList.length > 0 &&
        dataList.map((shop) => (
          <View
            className="shop"
            key={'recTakeOutOrgShop' + shop.id + Math.random()}
            onClick={() => goShopDetail(shop.id, shop.merchantId)}
          >
            {shop.activityList &&
              shop.activityList.length > 0 &&
              shop.activityList.map((activity, idx) => {
                let src = '';
                if (activity.type == 1) {
                  //团餐
                  src = pTuancanbiaoqian;
                }
                if (activity.isShow == 1) {
                  return <Image className="tcIcon" src={src} key={'activity' + idx} />;
                } else {
                  return null;
                }
              })}
            <View className="left">
              <Imagelocation className="shopIcon" src={shop.logo} type="shop" />
            </View>
            <View className="right">
              <View className="name">{shop.name}</View>
              <View className="info">
                <View className="infoLeft">
                  <Image
                    className="starIcon"
                    src={typeof shop.grade !== 'undefined' ? pStar : ''}
                  />
                  <Text className="starNum">{shop.grade || ''}</Text>
                  <Text className="saleTitle">月售</Text>
                  <Text className="saleNum">
                    {typeof shop.saleNum !== 'undefined' ? shop.saleNum : 0}
                  </Text>
                </View>
                <View className="infoRight">
                  <Text className="sendTime">
                    {typeof shop.sendTime !== 'undefined' ? shop.sendTime + '分钟' : ''}
                  </Text>
                  <Text className="distance">
                    {typeof shop.distance !== 'undefined' ? shop.distance + 'km' : ''}
                  </Text>
                </View>
              </View>

              <StandServiceTags className="tags" serviceTags={shop.serviceTags} />

              <View className="fee">
                <Text className="mText">
                  {typeof shop.minMoney !== 'undefined' ? '起送¥' + shop.minMoney : ''}
                </Text>
                <Text className="mText">
                  {typeof shop.deliveryMoney !== 'undefined'
                    ? shop.deliveryMoney == 0
                      ? '免配送费'
                      : shop.deliveryMoney == -1
                      ? '超出配送范围'
                      : '配送费¥' + shop.deliveryMoney
                    : ''}
                </Text>
                <Text className="mText">
                  {typeof shop.peopleAvg !== 'undefined' ? '人均¥' + shop.peopleAvg : ''}
                </Text>
              </View>
              {shop.policy && shop.policy.length > 0 && (
                <View className="manjianLine">
                  {shop.policy.map((item, index) => (
                    <Text className="manjian" key={'manjian' + index}>
                      {item}
                    </Text>
                  ))}
                </View>
              )}
            </View>
          </View>
        ))}
    </View>
  );
};

const RecProduct = ({ dataList = [], dispatch }) => {
  return (
    <View className="recProduct" key="RecProduct">
      {dataList.length > 0 &&
        dataList.map((good, index) => (
          <View
            className="goodInfo"
            key={'theme' + good.id + '_' + index}
            onClick={() => utils.goGoodDetail(good, dispatch)}
          >
            <Imagelocation
              className="goodIcon"
              src={good.url?.indexOf('http') === 0 ? good.url : sourceUrl + good.url}
            />
            <View className="goodBase">
              {/* <Text className="goodName">{good.title}</Text> */}
              <ProductTitle product={good} />
              <Text className="goodPrice">¥{good.price}</Text>
              <Text className="goodSendType">已售卖{good.saleNum || 0}件</Text>
            </View>
          </View>
        ))}
    </View>
  );
};

export default connect(({ loading, productList, takeOut, otherApi }) => ({
  cheaperProductList: productList.cheaperProductList,
  shopProductList: productList.shopProductList,
  shopProductListFinished: productList.shopProductListFinished,
  takeOutOrgList: takeOut.takeOutOrgList,
  takeOutOrgFinished: takeOut.takeOutOrgFinished,
  advertInfo: otherApi.advertInfo,
  advertList: otherApi.advertList,
  localOrgList: otherApi.localOrgList,
  localOrgFinished: otherApi.localOrgFinished,
  navList: otherApi.navList,
  newShopOrgList: otherApi.newShopOrgList,
  loading,
}))(WrapPageLoadLoading(HomePage, { once: false, page: 'home' }));
